package com.atguigu.tingshu.dispatch.job;

import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.dispatch.mapper.XxlJobLogMapper;
import com.atguigu.tingshu.model.dispatch.XxlJobLog;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class UserDispatchJobHandler {
    @Resource
    private XxlJobLogMapper xxlJobLogMapper;
    @Resource
    private UserInfoFeignClient userInfoFeignClient;

    @XxlJob("UserUpdateVipStatus")
    public void UserUpdateVipStatus() {
        long startTime = System.currentTimeMillis();
        XxlJobLog xxlJobLog = new XxlJobLog();
        xxlJobLog.setJobId(XxlJobHelper.getJobId());
        try {
            Result result = this.userInfoFeignClient.updateVipStatus();
            if (result == null) {
                xxlJobLog.setStatus(0);
                xxlJobLog.setError("Vip状态修改时，远程调用失败！");
                XxlJobHelper.handleFail();
            } else {
                xxlJobLog.setStatus(1);
                XxlJobHelper.handleSuccess();
            }
        } catch (Exception e) {
            xxlJobLog.setStatus(0);
            xxlJobLog.setError("Vip状态修改时，服务器异常！" + e.getMessage());
            XxlJobHelper.handleFail();
            e.printStackTrace();
        } finally {
            long times = System.currentTimeMillis() - startTime;
            xxlJobLog.setTimes(Long.bitCount(times));
            this.xxlJobLogMapper.insert(xxlJobLog);
        }
    }
}
